#include "common.hpp"
#include "InetAddr.hpp"


void Usage(std::string str)
{
    LOG(LogLevel::FATAL) << "you should enter : " << str << "target ip + target port";
}

int main(int args, char* argv[])
{
    if(args != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    u_int16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    //1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error";
        exit(SOCKET_ERROR);
    }

    //2.和Udp一样，不需要显式的bind

    InetAddr Target(ip,port);
    //3.Tcp需要和服务端进行连接，此处需要将主机字节序转为网络字节序，
    //连接完毕后，通过read / write 进行文件操作
    int n = connect(sockfd, Target.NetAddrptr(), Target.NetAddrLen());
    if( n < 0)
    {
        LOG(LogLevel::FATAL) << "connect error";
        exit(CONNECT_ERROR);
    }

    while(true)
    {
        std::string line;
        std::cout << "please enter: " << std::endl;
        std::getline(std::cin,line);
    
        int n = write(sockfd,line.c_str(),line.size());
        if(n < 0)
            std::cout << "error" << std::endl;

        //echo
        char buffer[1024];
        ssize_t size  = read(sockfd,buffer,sizeof(buffer)-1);
        if(size > 0)
        {
            buffer[size] = 0;
            std::cout << "ehco# : " << buffer << std::endl;
        }
    }
    close(sockfd);

    return 0;
}